package handler;

import http.MyHttpRequest;
import pool.WriteTask;

import java.net.Socket;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author Karl
 * @Date 2023/1/2 - 16:15
 */
public class RedirectJudge {

    /**
     * 记录了从文件中读出来的需要重定向的原地址和目标
     */
    public static Map<String, String> redirectMap;
    private static String lineSeparator = System.lineSeparator();

    static {
        redirectMap = new HashMap<>();
        ResourceBundle bundle = ResourceBundle.getBundle("redirect");
        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement();
            redirectMap.put(key,bundle.getString(key));
        }
    }


    public static boolean needRedirect(MyHttpRequest request) {
        return redirectMap.containsKey(request.getHost());
    }

    public static void redirect(MyHttpRequest request){
        String oldHost = request.getHost();
        String newHost = redirectMap.get(oldHost);
        request.setHost(newHost);
        request.addRequestHeader("Host: "+newHost+lineSeparator);
        String line = request.getRequestLine();
        String replace = line.replace(oldHost, newHost);
        request.setRequestLine(replace);
    }
}
